
package jwww.service;

import java.io.IOException;
import java.net.*;

import org.apache.log4j.Logger;

public class WebServer
  extends Thread
{
  int port = 80;

  Service service = null;
  ServerSocket listener = null;
  boolean running = false;

  Logger logger = null;

  public WebServer(Service service, int port)
  {
    this.service = service;
    this.port    = port;
    logger = Logger.getLogger("JWWW");
  }

  @Override
  public void run()
  {
    running = true;
    service.initialize();
    try
    {
      listener = new ServerSocket(port);
      while (running)
      {
        Socket     socket  = listener.accept();
        ServerThread handler = new ServerThread(socket, service);
        handler.start();
      }
    }
    catch (BindException e)
    {
      logger.fatal("Could not use port: " + port);
      System.exit(1);
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }

  public void shutdown()
  {
    running = false;
    try
    {
      listener.close();
    }
    catch (IOException e)
    {
      System.out.println("listener not open.");
    }
  }
}
